package com.burger.burgerpicturebackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.burger.burgerpicturebackend.annotation.AuthCheck;
import com.burger.burgerpicturebackend.common.BaseResponse;
import com.burger.burgerpicturebackend.common.DeleteRequest;
import com.burger.burgerpicturebackend.common.ResultUtils;
import com.burger.burgerpicturebackend.constant.UserConstant;
import com.burger.burgerpicturebackend.exception.BusinessException;
import com.burger.burgerpicturebackend.exception.ErrorCode;
import com.burger.burgerpicturebackend.exception.ThrowUtils;
import com.burger.burgerpicturebackend.model.dto.category.CategoriesAddRequest;
import com.burger.burgerpicturebackend.model.dto.category.CategoriesQueryRequest;
import com.burger.burgerpicturebackend.model.entity.Categories;
import com.burger.burgerpicturebackend.model.entity.Categories;
import com.burger.burgerpicturebackend.model.entity.User;
import com.burger.burgerpicturebackend.service.CategoriesService;
import com.burger.burgerpicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 标签接口
 *
 */
@RestController
@RequestMapping("/categories")
@Slf4j
@CrossOrigin
public class CategoriesController {

    @Resource
    private CategoriesService categoryService;

    @Resource
    private UserService userService;

    @PostMapping("/addCategories")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<String> addCategories(CategoriesAddRequest categoriesAddRequest, HttpServletRequest request) {
        Categories categories = new Categories();
        String categoryName = categoriesAddRequest.getCategoryName();
        categories.setCategoryName(categoryName);
        categoryService.save(categories);
        return ResultUtils.success(categoryName);
    }


    @GetMapping("/get/categories")
    public BaseResponse<List<Categories>> getCategories(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        if (user==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录，请先登录");
        }
        QueryWrapper<Categories> queryWrapper = new QueryWrapper<>();
        List<Categories> categoryList = categoryService.list(queryWrapper);
        return ResultUtils.success(categoryList);
    }

    /**
     * 记录标签使用次数
     */
    @PostMapping("/record")
    public BaseResponse<Boolean> recordCategories(@RequestBody CategoriesAddRequest categoriesAddRequest, HttpServletRequest request) {
        QueryWrapper<Categories> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("categoryName", categoriesAddRequest.getCategoryName());
        Categories categories = categoryService.getOne(queryWrapper);
        categories.setUsageCount(categories.getUsageCount() + 1);
        categoryService.updateById(categories);
        return ResultUtils.success(true);
    }

    /**
     * 返回热门标签
     */
    @GetMapping("/hotCategories")
    public BaseResponse<List<Categories>> hotCategories(HttpServletRequest request) {
        QueryWrapper<Categories> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("usageCount");
        queryWrapper.last("limit 10");
        List<Categories> categoryList = categoryService.list(queryWrapper);
        return ResultUtils.success(categoryList);
    }

    /**
     * 分页获取标签列表（仅管理员可用）
     */
    @PostMapping("/search/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Categories>> listCategoriesByPage(@RequestBody CategoriesQueryRequest categorysQueryRequest) {
        long current = categorysQueryRequest.getCurrent();
        long size = categorysQueryRequest.getPageSize();
        // 查询数据库
        Page<Categories> categorysPage = categoryService.page(new Page<>(current, size)
                , categoryService.getQueryWrapper(categorysQueryRequest));
        return ResultUtils.success(categorysPage);
    }

    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteCategory(@RequestBody DeleteRequest deleteRequest
            , HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = deleteRequest.getId();
        // 判断是否存在
        Categories oldTag = categoryService.getById(id);
        ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = categoryService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

}
